/**
 * AttachmentController.java
 * Created at 2017-07-13
 * Created by Jackie liu
 * Copyright (C) 2014, All rights reserved.
 */
package com.huabo.controller.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huabo.base.BaseController;
import com.huabo.file.FileOperation;
import com.huabo.model.Attachment;
import com.huabo.model.User;
import com.huabo.service.inter.AttachmentService;
import com.huabo.utils.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>ClassName: AttachmentController</p>
 * <p>Description: 通用附件管理Controller</p>
 * <p>Author: Jackie liu</p>
 * <p>Date: 2017-07-13</p>
 */
@Controller
public class AttachmentController extends BaseController {

    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private FileOperation fileOperation;
    @Value("${file.request.url}")
    private String fileRequestUrl;

    /**
     * 上传附件
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/attachment/upload", method = RequestMethod.POST)
    @ResponseBody
    public Response upload(HttpServletRequest request, HttpServletResponse response) {
        try {
            //创建一个通用的多部分解析器
            CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

            List<MultipartFile> fileList = null;
            //判断是否有文件上传,即多部分请求
            if (resolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multiReq = (MultipartHttpServletRequest) request;
                fileList = multiReq.getFiles("files");
            }
            if (fileList == null || fileList.isEmpty()) {
                return ResponseUtils.warn("上传文件为空");
            }

            final List<Attachment> list = new ArrayList<Attachment>();
            User user = ApiUtils.getLoginUser(request);
            JSONArray jsonArray = new JSONArray();
            for (MultipartFile file : fileList) {
                if (file.getSize() <= 0) {
                    continue;
                }
                Attachment uploadFile = new Attachment();
                list.add(uploadFile);

                uploadFile.setId(KeyUtils.getDistributedId());
                uploadFile.setRefId(Constants.DEFAULT_VALUE);
                uploadFile.setCreateTime(new Date());
                uploadFile.setCreateId(user.getId());
                uploadFile.setSize(file.getSize());
                uploadFile.setOriginalName(file.getOriginalFilename());
                uploadFile.setCategory(0);

                String[] pics = {"jpg", "png", "jpeg", "gif", "bmp"};
                String extName = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
                if (Arrays.asList(pics).indexOf(extName) >= 0) {
                    uploadFile.setType("pic");
                } else {
                    uploadFile.setType(extName);
                }

                String fileName = fileOperation.save(file.getInputStream(), KeyUtils.getKey() + "." + extName);

                uploadFile.setPath(fileName);

                JSONObject json = new JSONObject();
                json.put("id", uploadFile.getId());
                json.put("name", uploadFile.getOriginalName());
                json.put("path", uploadFile.getPath());
                jsonArray.add(json);
            }

            attachmentService.batchSave(list);

            return ResponseUtils.success(jsonArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseUtils.error("上传文件失败");
    }

    /**
     * 下载附件
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/attachment/download", method = {RequestMethod.POST, RequestMethod.GET})
    public String download(HttpServletRequest request, HttpServletResponse response) {
        long id = ServletRequestUtils.getLongParameter(request, "id", -1);
        return downloadPath(id, request, response);
    }

    /**
     * 下载附件
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/attachment/download/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    public String downloadPath(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        if (id == null) {
            AjaxUtils.ajaxText(response, "参数错误");
            return null;
        }
        Attachment attachment = attachmentService.load(id);
        if (attachment == null) {
            AjaxUtils.ajaxText(response, "该文件不存在");
            return null;
        }
        return new StringBuilder().append("redirect:").append(fileRequestUrl)
                .append(attachment.getPath()).append("?filename=").append(attachment.getOriginalName()).toString();
    }

    /**
     * 将文件转成base64字符串
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/attachment/read/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response readBase64(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        if (id == null) {
            AjaxUtils.ajaxText(response, "参数错误");
            return null;
        }
        Attachment attachment = attachmentService.load(id);
        if (attachment == null) {
            AjaxUtils.ajaxText(response, "该文件不存在");
            return null;
        }

        byte[] byteArray = fileOperation.read(attachment.getPath());
        if (byteArray == null) {
            return ResponseUtils.warn("文件转码错误");
        }
        return ResponseUtils.success("success", Base64.encodeBase64String(byteArray));
    }
}
